﻿using System;
using System.Linq;

using Microsoft.Phone.Controls;
using System.Windows.Controls;
using BismillahReader.Core;
using Microsoft.Phone.Shell;

namespace BismillahReader
{
    public partial class SurahView : PhoneApplicationPage
    {
        public SurahView()
        {
            InitializeComponent();
        }

        private int _ayahNo = 0;
        private int _surahNo = 0;

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string fontName = AppContext.CurrentTranslation.Font;
            if (string.IsNullOrEmpty(fontName))
            {
                lstSurah.FontFamily = new System.Windows.Media.FontFamily(@".\Fonts\Ubuntu-M.ttf#Ubuntu Light");
            }
            else
            {
                lstSurah.FontFamily = new System.Windows.Media.FontFamily(fontName);
            }
            //int no = int.Parse(NavigationContext.QueryString["no"]);
            this.DataContext = AppContext.Surah;
            _surahNo = AppContext.Surah.No;
        }

        bool _keepPlaying = false;

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            ApplicationBarMenuItem mnu = sender as ApplicationBarMenuItem;
            if (mnu != null)
            {
                if (mnu.Text == "Recite")
                {
                    PlayNext(); 
                    _keepPlaying = true;
                }
                else if (mnu.Text == "Stop")
                {
                    _keepPlaying = false;
                    mp3.Stop();
                }
            }
        }

        private void mp3_MediaEnded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (_keepPlaying)
            {
                PlayNext();
            }
        }

        private void PlayNext()
        {
            try
            {
                Uri uri = QuranTranslation.GetUrl(_surahNo, _ayahNo, false);
                mp3.Source = uri;
                mp3.Play();
                _ayahNo++;
                lstSurah.SelectedIndex = _ayahNo - 2;
            }
            catch
            {
                _keepPlaying = false;
            }
        }

        private void lstSurah_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _ayahNo = lstSurah.SelectedIndex + 2;
        }
    }
}